import React, { useState, useEffect, useCallback } from 'react';
import { List } from 'react-vant';
import { Toast, Input, Modal, Dialog } from 'antd-mobile';
import { useLocation } from 'react-router-dom';
import Loading from '@/components/Loading';
import HeadTop from '@/components/HeadTop';
import ListItem from './ListItemCheck';
import FooterCheck from '@/components/FooterCheck/index';
import PickerSelect from '@/components/PickerSelect';
import { menuTab, listFields, listdata } from './const';
import './index.less';
import ApiIndex from '@/api/approve.js';

const Index = ({ history }) => {
    const [list, setList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [finished, setFinished] = useState(false);
    const [activeTab, setactiveTab] = useState('1'); // tab切换
    const [isAllcheck, setisAllcheck] = useState(false); // 全选状态

    const [value, setValue] = useState('');
    const [value2, setValue2] = useState('');
    const [selectedIds, setSelectedIds] = useState([])
    const location = useLocation();
    const title = new URLSearchParams(location.search).get('title');

    const [basicColumns, setbasicColumns] = useState([
        [
            { label: '上午', value: 'am' },
            { label: '下午', value: 'pm' },
        ],
    ]); // 设备类型

    // 修改采购单
    const [no, setNo] = useState();

    useEffect(() => {
        getRequestData();
    }, []);

    const getRequestData = async () => {
        setLoading(true)
        let params = {
            page: 1,
            size: 9999,
            type: 'IN',
            status:'WAIT_CHECK',
            createUserName:value || '',
            purchaseOrder:value2 || ''

        }
        let res = await ApiIndex.approvalToolIoRecord(params)
        setLoading(false)
        if (res.data.code) {
            Toast.show({
                content: '请求失败:' + res.data.msg,
            })
            return
        }
        let list = res.data.data.records
        const newList = list.map(el => ({ ...el, check: false }));
        setList(newList)
        setFinished(true)
        setLoading(false)
        setSelectedIds([])
        // if (res.data.data.records.length) {
         
        // }
        // setTimeout(() => {
        //     const newList = listdata.map((el) => ({ ...el, check: false }));
        //     setList(newList);
        //     setFinished(true);
        //     setLoading(false);
        // }, 500);
    };

    const handleSubmitBtn = (type) => {

        setLoading(true);
        // let obj = {
        //     ids:selectedIds,
        //     passedOrNot:review[0] == '通过' ? 'Y' : 'N',
        //     reason:inputvalue
        // }
        // console.log(selectedIds,1111)
        ApiIndex.approvalCheckActNum(selectedIds.join(',')).then(res =>{
            console.log(res,222)
            if(res.data.success){
                // console.log(332)
                setLoading(false);
                getRequestData()
                Toast.show({
                    content: '操作成功',
                })
            }
            
        })
        setTimeout(() => {
            setLoading(false);
        }, 500);
    };

    const itemHandleCheck = (item) => {

        const newList = list.map(el =>
            el.no === item.no ? { ...el, check: !el.check } : el
        )
        const newSelectedIds = newList.reduce((acc, currentItem) => {
            if (currentItem.check && currentItem.no === item.no) {
                return [...acc, currentItem.no]
            } else if (!currentItem.check && currentItem.no === item.no) {
                return acc.filter(no => no !== currentItem.no)
            }
            return acc
        }, [...selectedIds])
        
        setList(newList)
        setSelectedIds(newSelectedIds)

        const allChecked = newList.every(el => el.check)
        setisAllcheck(allChecked)
    }

    const handlesetAllcheck = (e) => {
        let newSelectedIds = []
        if(e){
             newSelectedIds = list.map(item => item.no)
        }else {
            newSelectedIds = []
        }
        setSelectedIds(newSelectedIds);
        const newList = list.map((el) => ({ ...el, check: e }));
        setList(newList);
        setisAllcheck(e);
    };
    const personClick =() =>{
        getRequestData()
    }
    const purchaseClick =() =>{
        getRequestData()
    }
    const setSelectVal = (v) => {
        console.log(v);
    };

    const itemHandleEditValue = (no) => {
        Dialog.confirm({
            content: <EditModal no={no} onConfirm={handleConfirm} onCancel={() => {}} />,
            onConfirm: () => {},
            onCancel: () => {},
        });
    };

    const handleConfirm = (newNo) => {
        console.log('新的采购单号:', newNo);
        setNo(newNo);
        getRequestData();
    };

    const EditModal = ({ no, onConfirm, onCancel }) => {
        const [localNo, setLocalNo] = useState(no);

        useEffect(() => {
            setLocalNo(no);
        }, [no]);

        const handleSave = () => {
            onConfirm(localNo);
        };

        return (
            <div style={{ display: 'flex', flexDirection: 'column' }}>
                <div className="modal-tit" style={{ fontSize: '14px', textAlign: 'center' }}>修改采购单</div>
                <div className='modal-content'>
                    <Input
                        placeholder='请输入采购单'
                        className='select-line'
                        value={localNo}
                        onChange={(val) => setLocalNo(val)}
                    />
                </div>
            </div>
        );
    };

    return (
        <div className='page-wrapper'>
            {loading ? <Loading></Loading> : null}
            <HeadTop title={title} history={history}></HeadTop>
            <div className="select-pan">
                <Input
                    placeholder='请输入申请人'
                    value={value}
                    className='select-line'
                    onChange={(val) => setValue(val)}
                    onEnterPress={personClick}
                ></Input>
                <div style={{ height: 6 }}></div>
                <Input
                    placeholder='请输入采购单'
                    value={value2}
                    className='select-line'
                    onChange={(val) => setValue2(val)}
                    onEnterPress={purchaseClick}
                ></Input>
            </div>

            <div className="page-body" style={{ padding: 15 }}>
                <List finished={finished} errorText='请求失败，点击重新加载'>
                    {list.map((el) => (
                        <ListItem
                            key={el.id}
                            item={el}
                            listFields={listFields}
                            emitCheck={itemHandleCheck}
                            emitEditValue={(value) => itemHandleEditValue(value, el)}
                        ></ListItem>
                    ))}
                    {finished ? <div className='loadingTxt'>无更多数据</div> : null}
                </List>
            </div>
            <FooterCheck
                hasCheck={true}
                isAllcheck={isAllcheck}
                sureBtnTxt="批量审核"
                emitSetAllcheck={handlesetAllcheck}
                emitSubmitBtn={handleSubmitBtn}
            ></FooterCheck>
        </div>
    );
};

export default Index;